#include "storage_interface.h"

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>  
#include <fcntl.h>  
#include <sys/types.h>  
#include <sys/stat.h> 

error_e get_storage_cfg_info(const unsigned char *file_name, void *ctx, unsigned int lenght, dido_get_e type)
{   
    int fd = open(file_name, O_RDONLY | O_CREAT, S_IRUSR);  
    if (STO_FAIL == fd) 
    {      
        printf("open %s fail!\n", file_name);
        return STO_NO_DATA;   
    }

    read(fd, ctx, lenght);
    close(fd); 

    if (type == DIDO_REALTIME && strcmp(file_name, DIDO_FILE_NEME) == 0)
    {
        unsigned char val;
        getAllDigiInput(&val);
        dido_config_t *dido = (dido_config_t *) ctx;
        dido->di_val.val = val^0x3f;     /* DI的信息是 默认为1，有输入为0。与我们想要的结果正好相反 */
        /* 获取实时DO信息 */
        // getAllDigiOutput(&dido->do_val);
    }
    
    return STO_SUCCESS;
}

error_e set_storage_cfg_info(const unsigned char *file_name, void *ctx, unsigned int lenght)
{
    int fd = open(file_name, O_WRONLY | O_CREAT, S_IWUSR);  
    if (STO_FAIL == fd) 
    {      
        printf("open %s fail!\n", file_name);
        return STO_NO_DATA;   
    } 

    write(fd, ctx, lenght);
    close(fd); 
    
    return STO_SUCCESS;
}

/* IP地址 字符串 转 unsigned int */
unsigned int ip_to_int(const char *ip_str) 
{
    unsigned int result = 0;
    int octet;
    char *ip_copy = strdup(ip_str);         // 复制 IP 字符串以便修改
    char *token;
    const char *delimiter = ".";

    // 使用 strtok 遍历每个八位字节
    token = strtok(ip_copy, delimiter);
    for (int i = 0; i < 4 && token != NULL; ++i) {
        octet = atoi(token);                // 将字符串转换为整数
        if (octet < 0 || octet > 255) {
            fprintf(stderr, "Invalid octet: %s\n", token);
            free(ip_copy);
            return 0;
        }
        result = (result << 8) | octet;     // 将八位字节加入结果
        token = strtok(NULL, delimiter);
    }

    free(ip_copy);
    return result;
}

/* IP地址 unsigned int 转 字符串 */
void int_to_ip(unsigned int ip_int, char *ip_str)
{
    unsigned char bytes[4];
    
    bytes[0] = (ip_int >> 24) & 0xFF;
    bytes[1] = (ip_int >> 16) & 0xFF;
    bytes[2] = (ip_int >> 8) & 0xFF;
    bytes[3] = ip_int & 0xFF;
    
    snprintf(ip_str, IP_ADDR_STR_LEN, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], bytes[3]);
}